package com.wenjiang.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wenjiang.config.AliPayConfig;
import com.wenjiang.entity.AliPayBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.stereotype.Service;

import java.util.logging.Logger;

@Service
@Slf4j
public class AliPayServiceImpl {
    @Autowired
    AliPayConfig aliPayConfig;

    //发送一个支付请求连接

    public String alipay(AliPayBean aliPayBean) throws AlipayApiException, JsonProcessingException {
        //获取配置的属性

        String getway = aliPayConfig.getGatewayUrl();
        String appId= aliPayConfig.getAppId();
        String privatekey=aliPayConfig.getPrivateKey();
        String publickey = aliPayConfig.getPublicKey();
        String format="json";
        String signtype = aliPayConfig.getSignType();
        String charset = aliPayConfig.getCharset();
        String returnurl=aliPayConfig.getReturnUrl();
        String notifyurl=aliPayConfig.getNotifyUrl();
        //添加配置
        AlipayClient alipayClient = new DefaultAlipayClient(getway, appId, privatekey, format, charset, publickey, signtype);
        // 设置请求参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyurl);
        request.setReturnUrl(returnurl);

        //封装订单信息
        ObjectMapper objectMapper = new ObjectMapper();

        String content=objectMapper.writeValueAsString(aliPayBean);
        log.info(content);

        request.setBizContent(content);

        //3.请求支付宝进行付款 并获取支付结果
        String result = alipayClient.pageExecute(request).getBody();

        return result;
    }
}
